<template>
    <a-modal
            v-model="modal1"
            title="重置用户PIN码"
            :maskClosable="false"
            :destroyOnClose="true"
            @cancel="cancel"
    >
        <div>
            <a-form :form="form" class="modelSearch">
                <a-form-item label="安全UKey" v-bind="formStyle" :extra="devMsg">
                    <a-input v-model="resetPinCodeForm.serialNum" disabled/>
                </a-form-item>
                <a-form-item label="系统用户" v-bind="formStyle">
                  <a-input v-model="resetPinCodeForm.userName" disabled/>
                </a-form-item>
                <a-form-item label="管理员密码" v-bind="formStyle" :extra="msg">
                    <a-input :type="pwdType" v-model="resetPinCodeForm.szAdminPin" placeholder="请输入管理员密码" style="position: relative;"
                             @change="validePassword(resetPinCodeForm.szAdminPin)" >
                        <a-icon slot="suffix" :type="eyeStatusName" @click="showPwd" style="color: rgba(0,0,0,.65)" />
                    </a-input>
                </a-form-item>
                <!-- 登录页驱动下载处理 -->
                <div>
                    <span v-if ='showLoadUrl' style="font-size: 16px;color: #419aff;cursor: pointer;float: right;margin-top: -20px;margin-right: 13px;"
                          @click="downLoadUkeyDevice()" >下载UKey实体鉴别客户端</span>
                    <iframe id="ifile" title="下载UKey实体鉴别客户端" style="display: none"></iframe>
                </div>
            </a-form>
            <div style="margin-top: 20px">
                <span style="color: red">验证规则:</span>
                <br/>
                <span style="color: red">1、密码不能为空</span>
                <br/>
                <span style="color: red">2、密码应满足长度6-16字符，且只能是字母和数字</span>
            </div>
        </div>
        <div slot="footer">
            <a-button type="default" @click="cancel('resetPinCodeForm')">取消</a-button>
            <a-button type="primary" @click="resetUserPin('resetPinCodeForm')" :disabled="disabledBtn">确定</a-button>
        </div>
    </a-modal>
</template>

<script>
  import util from 'libs/util.js';
  import * as State from "libs/baseStateConts";
  const Base64 = require('js-base64').Base64;
  export default {
      name: 'resetPinCode',
      data () {
          const pwdregT= /^[a-zA-Z0-9_]+$/;
          const validePassword = (rule, value, callback) => {
            if (!value || value.trim().length === 0) {
              callback(new Error('必填项'));
            }else if(value.length > 16 || value.length < 6){
              callback(new Error('请输入6-16位有效密码！'));
            }else if (!pwdregT.test(value)) {
              callback(new Error('请输入包含大小写字母或数字的有效密码！'));
            }  else {
              callback();
            }
          };

          return {
              scanUKeyTimer: -1,
              showLoadUrl:false,
              form: this.$form.createForm(this),
              formStyle: {
                  labelCol: { span: 6 },
                  wrapperCol: { span: 17 }
              },
              modal1: false,
              pwdType: 'password', // 密码框显示密码的控制
              eyeStatusName: 'eye-disabled', // 密码框显示密码的图标展示控制
              resetPinCodeForm: {
                  serialNum:'',
                  userName:'',
                  szAdminPin: ''
              },
              devMsg:'',
              szAdminPinError: '',
              passwordValidate: {
                  serialNum:[
                      { required: true, message: '请插入安全UKey', trigger: 'blur' }
                  ],
                  szAdminPin: [
                      { required: true, trigger: 'blur', validator: validePassword }
                  ]
              },
              msg:'',
              disabledBtn: false

          }
      },
      methods: {
          validePassword(value){
              this.msg = ''
              let pwdregT= /^[a-zA-Z0-9_]+$/;
              if (!value || value.trim ().length === 0) {
                  this.msg = '请输入6-16位有效密码'
              } else if (value.trim ().length < 6 || value.trim ().length > 16) {
                  this.msg = '请输入6-16位有效密码'
              }else if (!pwdregT.test(value)) {
                  this.msg = '请输入包含大小写字母或数字的有效密码！'
              }
          },

          /**
           * Function    : startScanTimer
           * Description : 开启扫描UKey设备定时器
           * Input       : None
           * Return      : None
           */
          startScanTimer() {
              let _this = this;
              if (_this.scanUKeyTimer !== -1) {
                  return;
              }

              //开启扫描外接密钥存储设备定时器
              _this.scanUKeyTimer = setInterval(function() {
                  _this.updDevSerialNum ();
              }, 1000 * 1);
          },

          /**
           * Function    : updDevSerialNum
           * Description : 更新UKey设备序列号
           * Input       : None
           * Return      : None
           */
          updDevSerialNum () {
              let _this = this;
              _this.$axios.get(this.$uurl+'/ukeyauth/getAuthDevSerialNum').then(response => {
                  let respData = response.data;
                  _this.showLoadUrl = false;
                  if (respData.code !== 0 || respData.data === '')  {
                      _this.resetPinCodeForm.serialNum = '';
                      _this.resetPinCodeForm.userName ='';
                      _this.resetPinCodeForm.szAdminPin='';

                      _this.devMsg = '请插入安全UKey';
                      return ;
                  }


                  if (_this.resetPinCodeForm.serialNum !== respData.data)  {
                    _this.resetPinCodeForm.serialNum = respData.data;
                    let params = Object.assign({}, {authType: State.LOGIC_NUM_FALSE});
                    _this.$axios.post(this.$uurl+'/authmanager/getAuthUkeyDevReqParams',params,{}).then(response => {
                      let respData = response.data;
                      if (respData.code !== 0) {
                        _this.devMsg = respData.message;
                        return ;
                      }

                      params = Object.assign({}, respData.data);
                      this.$store.dispatch('getSysUserByUKeyAct', params).then(response => {
                        if (response.code !== 0) {
                          _this.devMsg = response.message;
                          return;
                        }
                        respData = response.data;
                        if (respData.authStatus === State.LOGIC_NUM_FALSE) {
                          _this.devMsg = "UKey未在系统中授权用户";
                          _this.disabledBtn = true;
                          return;
                        }
                        _this.resetPinCodeForm.userName = respData.userName;
                        _this.devMsg = '';
                        _this.disabledBtn = false;
                      }).catch( e => {
                      });
                    }).catch( e => {

                    });
                  }

              }).catch( e => {
                  _this.clearScanTimer();
                  _this.showLoadUrl = true;
              });
          },

          /**
           * Function    : downLoadUkeyDevice
           * Description : 下载U盾认证登录驱动
           * Input       : None
           * Return      : None
           */
          downLoadUkeyDevice() {
            document.getElementById ('ifile').src = State.downloadUKeyAuthTool;
          },

          /**
           * Function    : clearScanTimer
           * Description : 关闭扫描UKey设备定时器
           * Input       : None
           * Return      : None
           */
          clearScanTimer () {
              let _this = this;
              //关闭定时器、并且提示用户出错信息
              if (_this.scanUKeyTimer === -1) {
                  return;
              }
              clearInterval(_this.scanUKeyTimer);
              _this.scanUKeyTimer = -1;
            },

          /**
           * Function    : showPwd
           * Description : 是否明码展示所填密码
           * Input       : None
           * Return      : None
           */
           showPwd () {
               let _this = this;
               if (_this.pwdType === 'password') {
                  _this.pwdType = 'text';
                  _this.eyeStatusName = 'eye';
               } else {
                  _this.pwdType = 'password';
                  _this.eyeStatusName = 'eye-disabled';
               }
           },

          /**
           * Function    : cancelEditPinCode
           * Description : 取消修改PIN码
           * Input       : resetPinCodeForm
           * Return      : None
           */
          cancel (resetPinCodeForm) {
              let _this = this;
              _this.resetPinCodeForm={
                  serialNum:'',
                    userName:'',
                    szAdminPin: ''
              }
               _this.devMsg = '';
               _this.msg = '';
              _this.clearScanTimer ();
              _this.modal1 = false;
           },

          /**
           * Function    : resetUserPin
           * Description : 重置用户PIN码
           * Input       : editForm 管理员PIN码
           * Return      : None
           */
          resetUserPin (resetPinCodeForm) {
              let _this = this;
              if(_this.devMsg === '' && this.msg === ''){
                  _this.devMsg = '';
                  _this.msg = '';
                  let szAdminPin = util.empty(Base64.encode(_this.resetPinCodeForm.szAdminPin));
                  let params =  Object.assign({},{ 'szAdminPin':szAdminPin });
                  _this.$axios.get(this.$uurl+'/ukeyauth/resetUserPin', {params:params}).then(response => {
                      response = response.data;
                      if (response.code === 0) {
                          this.$message.success({
                              content: '重置用户PIN码成功！PIN码为111111',
                              duration: 7,
                              onClose: true
                          })
                          _this.cancel (resetPinCodeForm);
                      } else {
                          _this.msg = response.message;
                      }
                  }).catch( e => {
                  });
              }
          },

          showModal () {
              this.startScanTimer();
              this.modal1 = true
              this.resetPinCodeForm.szAdminPin=''
          }
      }
  }
</script>
<style lang="less" scoped>

</style>
